#include "py_function_extension.hpp"
#include "scripting/scripting_api.h"
#include "scripting/scripting_module.h"
#include <fmt/format.h>

#include <Python.h>
#include <compile.h>
#include <import.h>
#include <object.h>
#include <pybind11/gil.h>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pyerrors.h>

PythonFunctionScript::PythonFunctionScript(std::string title, const std::string &script_path): IFunctionalScript(std::move(title), script_path, g_current_module)
{
    
}

PythonFunctionScript::~PythonFunctionScript()
{
    
}

void PythonFunctionScript::execute()
{
    py::gil_scoped_acquire gil;
    m_.attr("main")();
}

IScript* PythonFunctionScript::create(std::string title, std::string_view code, const std::string &script_path)
{
    auto script = new PythonFunctionScript(std::move(title), script_path);
    if (!script->compile(code)) {
        delete script;
        script = nullptr;
    }
    return script;
}

bool PythonFunctionScript::compile(const std::string_view& code)
{
    std::string name = fmt::format("function_{:X}", (uintptr_t)this);
    return compile_module_code(code.data(), name.c_str());
}
